package edu.cdnu.service.impl;

import java.util.List;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import edu.cdnu.dao.StudentDao;
import edu.cdnu.pojo.StudentPojo;
import edu.cdnu.service.StudentService;

@Service
public class StudentServiceImpl implements StudentService {

	@Autowired
	private StudentDao studentDao;
	
	@Override
	public StudentPojo selectStudentById(int id) {
		return studentDao.selectStudentById(id);
	}

	@Override
	public List<StudentPojo> selectStudentListByIdList(List<Integer> idList) {
		if(idList != null && idList.size() > 0) {
			return studentDao.selectStudentListByIdList(idList);
		}else {
			return null;
		}
	}
	
	@Override
	public List<StudentPojo> selectAllStudentList() {
		return studentDao.selectAllStudentList();
	}

	@Override
	public void addStudent(StudentPojo studentPojo) {
		// 先判空，这里账号，密码，姓名为必须字段
		if(studentPojo != null 
				// 这里判空对象是可以用!=null的，后面空字符就需要空字符写在equals前面
				&& studentPojo.getAccount() != null && !"".equals(studentPojo.getAccount())
				&& studentPojo.getName() != null && !"".equals(studentPojo.getName())
				) {
			// 1.判断密码,为空给默认值
			if(studentPojo.getPassword() == null || "".equals(studentPojo.getPassword())) {
				studentPojo.setPassword("123456");
			}
			// 2.先把密码加密  用账号作盐
			Md5Hash md5=new Md5Hash(studentPojo.getPassword(),studentPojo.getAccount());
			studentPojo.setPassword(md5.toString());
			// 新增加密后的用户信息
			studentDao.addStudent(studentPojo);
		}
	}

	@Override
	public void updateStudent(StudentPojo studentPojo) {
		if(studentPojo != null && studentPojo.getId() != null) {
			studentDao.updateStudent(studentPojo);
		}
	}

	@Override
	public StudentPojo selectStudent(StudentPojo student) {
		// 先判空
		if(student==null) {
			return null;
		}
		QueryWrapper<StudentPojo> queryWrapper=new QueryWrapper<>();
		// id
		if(student.getId()!=null) {
			queryWrapper.eq("id", student.getId());
		}
		// role_id 不用判断
		// account 
		if(student.getAccount()!=null && !"".equals(student.getAccount())) {
			queryWrapper.eq("account", student.getAccount());
		}
		// password 不用判断
		// name
		if(student.getName()!=null && !"".equals(student.getName())) {
			queryWrapper.eq("name", student.getName());
		}
		// idcard 
		if(student.getIdcard()!=null & !"".equals(student.getIdcard())) {
			queryWrapper.eq("idcard",student.getIdcard());
		}
		// phone
		if(student.getPhone()!=null && !"".equals(student.getPhone())) {
			queryWrapper.eq("phone", student.getPhone());
		}
		// email
		if(student.getEmail()!=null && !"".equals(student.getEmail())) {
			queryWrapper.eq("eamil", student.getEmail());
		}
		// class_id
		if(student.getClassId()!=null) {
			queryWrapper.eq("class_id",student.getClassId());
		}
		return studentDao.selectOne(queryWrapper);
	}

}
